using UnityEngine;
using System.Collections;

public class moveShipSpace : MonoBehaviour
{
    public float speed;
    public int health = 10;
    public int score = 0;
    public bool isDeath = false;
    public GUIStyle myStyleScore;

    // Use this for initialization
    void Start()
    {
        // Keep the mobile screen active all the time.
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
    }

    // Update is called once per frame
    void Update()
    {
		// Exit if native Back-button is clicked
        if( Input.GetKeyDown(KeyCode.Escape) ) {
            Application.LoadLevel("Menu");
        }
		
        // Get the accelometer x-axis to move the hand.
        Vector3 movement = new Vector3(-Input.acceleration.x, -4, -0.5f);
        // test with the buttons.
        //Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), -4, -0.5f);
        
		// Give the speed for the hand and
		// restrict it not to disappear from the screen.
		transform.Translate(movement * Time.deltaTime * speed);
        transform.position = new Vector3(Mathf.Clamp(transform.position.x, -7.3f, 7.3f), -4, -0.5f);
        
		// Keep score as long as the ship is alive.
        if (isDeath == false)
        {
            score++;
        }
        if (health <= 0)
        {
            health = 0;
            isDeath = true;
            StartCoroutine(waitForQuit());
        }
    }

    IEnumerator waitForQuit()
    {
        // Sets the score from this game.
		GM.LastScore = score;
        yield return new WaitForSeconds(5);
        Application.LoadLevel(2);
    }

    // Shows the score in screen to player.
    void OnGUI()
    {
        AutoResize(480,320);
        GUI.Label(new Rect(0, 5, Screen.width, Screen.height), "Score:" + score, myStyleScore);
        GUI.Label(new Rect(300, 5, Screen.width, Screen.height), "Health:" + health, myStyleScore);
        if (isDeath == true)
        {
            GUI.Label(new Rect(190, 160,100, 40), "Peli ohi", myStyleScore);
        }
    }

    // Colliding with the balls.
    void OnTriggerEnter(Collider col)
    {
        if (isDeath == false)
        {
			// Makes the collided object to disappear and get extra points
            col.renderer.enabled = false;
            score += 50;
        }
    }

    public static void AutoResize(int screenWidth, int screenHeight)
    {
        Vector2 resizeRatio = new Vector2((float)Screen.width / screenWidth, (float)Screen.height / screenHeight);
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(resizeRatio.x, resizeRatio.y, 1.0f));
    }
}
